<template>
  <!-- 新增弹窗 -->
  <el-dialog
    :title="isEit?'编辑人员基础信息':'新增人员基础信息'"
    :visible.sync="dialogFormVisible"
    @close="closeBox"
  >
    <el-form
      :model="form"
      :rules="rules"
      ref="baseModalForm"
      label-width="120px"
      size="mini"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="身份证号" prop="identityNo">
            <el-input
              size="mini"
              class="inputW"
              v-model="form.identityNo"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item required label="姓名" prop="name">
            <el-input
              class="inputW"
              v-model="form.name"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="头像">
            <el-upload
              class="avatar-uploader"
              :action="picUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="头像"/>
              <em v-else class="el-icon-plus avatar-uploader-icon"></em>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item required label="单位名称" prop="company">
            <el-cascader
                ref="Company"
              class="inputW"
              v-model="form.company"
              :show-all-levels="false"
              :props="{ value: 'uuid', label: 'name',expandTrigger: 'hover',checkStrictly: true }"
              :options="companyOptions"
              @change="selectCompany"
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="部门名称" prop="department">
            <el-cascader
              ref="Department"
              class="inputW"
              placeholder="请选择部门名称"
              v-model="form.department"
              :show-all-levels="false"
              :props="{ value: 'uuid', label: 'name',expandTrigger: 'hover',checkStrictly: true }"
              :options="departmentOptions"
              @change="selectDepartment"
            ></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item required label="性别" prop="sex">
            <el-radio-group v-model="form.sex">
              <el-radio
                  v-for="(sexDict_item) in sexDict"
                  :label="sexDict_item.uuid"
                  :key="sexDict_item.uuid"
                  :value="sexDict_item.uuid"
              >{{sexDict_item.name}}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item required label="出生年月" prop="birthday">
            <el-date-picker
              class="inputW"
              :picker-options="{ disabledDate: endNow }"
              value-format="yyyy-MM"
              v-model="form.birthday"
              type="month"
              placeholder="选择出生年月"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item required label="民族" prop="national">
            <el-select
              class="inputW"
              v-model="form.national"
              placeholder="请选择民族"
            >
              <el-option
                v-for="national in nationalDict"
                :label="national.name"
                :value="national.uuid"
                :key="national.uuid"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item required label="籍贯" prop="origin">
            <el-input
              class="inputW"
              v-model="form.origin"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出生地">
            <el-input
              class="inputW"
              v-model="form.birthplace"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item required label="年龄" prop="age">
            <el-input-number
              :min="1"
              :max="100"
              class="inputW"
              v-model="form.age"
              autocomplete="off"
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item required label="参加工作日期" prop="workDay">
            <el-date-picker
              class="inputW"
              :picker-options="{ disabledDate: endNow }"
              v-model="form.workDay"
              type="month"
              placeholder="选择参加工作日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="工龄">
            <el-input-number
              :min="0"
              :max="100"
              class="inputW"
              v-model="form.workAge"
              autocomplete="off"
            ></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="岗位/职务">
            <el-input
              class="inputW"
              v-model="form.position"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item required label="个人身份" prop="staffIdentity">
            <el-cascader
              class="inputW"
              v-model="form.staffIdentity"
              :props="{ value: 'uuid', label: 'name',checkStrictly: true }"
              :show-all-levels="false"
              :options="identityOptions"
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item required label="编制性质" prop="recordType">
            <el-select
              class="inputW"
              v-model="form.recordType"
              placeholder="请选择编制性质"
            >
              <el-option
                v-for="record in recordDict"
                :label="record.name"
                :value="record.uuid"
                :key="record.uuid"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="享受待遇级别">
            <el-select
              class="inputW"
              v-model="form.treatment"
              placeholder="请选择享受待遇级别"
            >
              <el-option
                v-for="treatment in treatmentDict"
                :label="treatment.name"
                :value="treatment.uuid"
                :key="treatment.uuid"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item required label="人才类别" prop="talentType">
            <el-select
              class="inputW"
              v-model="form.talentType"
              placeholder="请选择人才类别"
            >
              <el-option
                v-for="talentType in talentTypeDict"
                :label="talentType.name"
                :value="talentType.uuid"
                :key="talentType.uuid"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item required label="是否部管干部" prop="leader">
            <el-radio-group v-model="form.leader">
              <el-radio
                v-for="item in ynDict"
                :label="item.uuid"
                :value="item.uuid"
                :key="item.uuid"
              >{{item.name}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <we-button size="mini" @click="closeBox"
        >取 消</we-button
      >
      <we-button size="mini" type="primary" @click="submit">确 定</we-button>
    </div>
  </el-dialog>
  <!-- 新增弹窗 -->
</template>

<script>
import { getAction, postAction, putAction } from '@/api/manage'
import { parseTree } from '@/utils/util'
import WeButton from '@/components/WeButton'
import { checkIdcard } from '@/utils/reg'
import moment from 'moment'
import {baseStaff, opDictNew} from "@/api/apiUrl";


function validateIdentityNo (rule, value, callback) {
  if (checkIdcard(value)) {
    callback()
  } else {
    callback(new Error('无效的身份证号码'))
  }
}

export default {
  components: {
    WeButton
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    row: {},
    isEit: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    show () {
      this.dialogFormVisible = true
      this.imageUrl = this.row.photo
    },
    'form.birthday' (value) {
      this.form.age = moment().diff(moment(value), 'year')
    },
    'form.workDay' (value) {
      this.form.workAge = moment().diff(moment(value), 'year')
    }
  },
  data () {
    return {
      picUrl:  window.serverUrl.url + baseStaff.upload,
      dialogFormVisible: this.show,
      sexDict: [],
      recordDict: [],
      nationalDict: [],
      identityDict: [],
      treatmentDict: [],
      talentTypeDict: [],
      ynDict: [],
      identityOptions: [],
      departmentOptions: [],
      companyOptions: [],
      departmentList: [],
      imageUrl: '',
      rules: {
        identityNo: [
          {
            required: true,
            message: '请输入身份证号',
            trigger: ['change', 'blur']
          },
          {
            min: 18,
            max: 18,
            message: '长度必须是 18 个字符',
            trigger: ['change', 'blur']
          },
          { validator: validateIdentityNo, trigger: ['change', 'blur'] }
        ],
        name: [
          {
            required: true,
            message: '请输入姓名',
            trigger: ['change', 'blur']
          }
        ],
        department: [
          {
            required: true,
            message: '请选择部门',
            trigger: ['change', 'blur']
          }
        ],
        company: [
          {
            required: true,
            message: '请选择单位',
            trigger: ['change', 'blur']
          }
        ],
        birthday: [
          {
            required: true,
            message: '请选择出生年月',
            trigger: ['change', 'blur']
          }
        ],
        national: [
          {
            required: true,
            message: '请选择民族',
            trigger: ['change', 'blur']
          }
        ],
        origin: [
          {
            required: true,
            message: '请填写籍贯',
            trigger: ['change', 'blur']
          }
        ],
        age: [
          {
            required: true,
            message: '请填写年龄',
            trigger: ['change', 'blur']
          }
        ],
        workDay: [
          {
            required: true,
            message: '请选择参加工作日期',
            trigger: ['change', 'blur']
          }
        ],
        staffIdentity: [
          {
            required: true,
            message: '请选择个人身份',
            trigger: ['change', 'blur']
          }
        ],
        sex: [
          {
            required: true,
            message: '请选择性别',
            trigger: ['change', 'blur']
          }
        ],
        recordType: [
          {
            required: true,
            message: '请选择编制性质',
            trigger: ['change', 'blur']
          }
        ],
        talentType: [
          {
            required: true,
            message: '请选择人才类别',
            trigger: ['change', 'blur']
          }
        ],
        leader: [
          {
            required: true,
            message: '请选择是否部管干部',
            trigger: ['change', 'blur']
          }
        ]
      },
      form: {
        identityNo: '',
        name: '',
        company: [],
        department: [],
        sex: '',
        birthday: '',
        age: 1,
        national: '',
        origin: '',
        birthplace: '',
        workDay: '',
        workAge: 0,
        position: '',
        staffIdentity: [],
        recordType: '',
        treatment: '',
        talentType: '',
        leader: ''
      },
      type: 'add'
    }
  },
  created () {
    if (this.row.uuid) {
      this.type = 'edit'
    }else{
      this.type = 'add'
      this.departmentOptions = []
    }
    this.form = this.row
    this.getDepartmentList('','company')
    if(this.form.company) { this.getDepartmentList(this.form.company,'department') }
    if(!this.imageUrl) {
      this.imageUrl = this.row.photo
    }
    if(this.$refs.baseModalForm) {
      this.$refs.baseModalForm.clearValidate()
    }

    this.getSex()
    this.getNational()
    this.getIdentity()
    this.getRecordType()
    this.getTreatment()
    this.getTalentType()
    this.getYn()
  },
  methods: {
    endNow (value) {
      const times = value.getTime()
      return times > Date.now()
    },
    /**
     * 获取树部门数据
     */
    async getDepartmentList(id,type) {
      const result = await getAction('/opDictNew/findTreeById',{ id: id,type: 'rs_department'})
      if (result.code === 200) {
        if(type === 'company') {
          this.departmentList = JSON.parse(JSON.stringify(result.data))
          this.companyOptions = result.data
        }else if(type === 'department') {
          this.departmentOptions = result.data
        }
      }
    },
    /**
     * 筛选单位
     */
    selectCompany() {
      let newList = this.$refs.Company.getCheckedNodes()[0]
      this.form.companyName = newList.label
      this.getDepartmentList(this.form.company[this.form.company.length-1],'department')
    },
    /**
     * 筛选部门
     */
    selectDepartment() {
      let node = this.$refs.Department.getCheckedNodes()[0]
      this.form.sysOrgCode = node.label
    },
    /**
     * 获取性别列表
     */
    async getSex () {
      const result = await getAction(opDictNew.findByType, {
        type: 'sex'
      })
      this.sexDict = result.data
    },
    /**
     * 获取是否列表
     */
    async getYn () {
      const result = await getAction(opDictNew.findByType, {
        type: 'yn'
      })
      this.ynDict = result.data
    },
    /**
     * 获取编制性质列表
     */
    async getRecordType () {
      const result = await getAction(opDictNew.findByType, {
        type: 'record_type'
      })
      this.recordDict = result.data
      console.log(this.recordDict)
    },
    /**
     * 获取编制性质列表
     */
    async getTalentType () {
      const result = await getAction(opDictNew.findByType, {
        type: 'talent_type'
      })
      this.talentTypeDict = result.data
    },
    /**
     * 获取享受待遇级别列表
     */
    async getTreatment () {
      const result = await getAction(opDictNew.findByType, {
        type: 'treatment'
      })
      this.treatmentDict = result.data
    },
    /**
     * 获取民族列表
     */
    async getNational () {
      const result = await getAction(opDictNew.findByType, { type: 'national' })
      this.nationalDict = result.data
    },
    /**
     * 获取身份列表
     */
    async getIdentity () {
      const result = await getAction('/opDictNew/findTreeByType', { type: 'identity' })
      this.identityDict = result.data
      this.identityOptions = parseTree(result.data)
    },
    handleAvatarSuccess (res, file) {
      // this.form.photo = res.data
      this.imageUrl = `${window.serverUrl.url}/${res.data}`
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2.5

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2.5MB!')
      }
      return isJPG && isLt2M
    },
    closeBox() {
      this.dialogFormVisible = false
      this.imageUrl = ''
      this.$emit('changeShowModal')
    },
    submit () {
      this.$refs.baseModalForm.validate((valid) => {
        if (valid) {
          const formData = JSON.parse(JSON.stringify(this.form))
          if (formData.department instanceof Array) {
            formData.department = formData.department.pop()
          }
          if (formData.company instanceof Array) {
            formData.company = formData.company.pop()
          }
          if (formData.staffIdentity instanceof Array) {
            formData.staffIdentity = formData.staffIdentity.pop()
          }
          formData.photo = this.imageUrl
          formData.baseCode = 'admin'
          formData.createUser = '测试员'
          formData.birthday = formData.birthday + '-01'
          if (this.type === 'add') {
            postAction(baseStaff.add, formData).then((res) => {
              console.log(res)
              this.imageUrl = ''
              this.dialogFormVisible = false
              this.$message.success({message: '新增成功!'})
              this.$emit('upData')
            })
          } else {
            postAction(baseStaff.update, formData).then((res) => {
              console.log(res)
              this.imageUrl = ''
              this.dialogFormVisible = false
              this.$message.success({message: '更新成功!'})
              this.$emit('upData')
            })
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.inputW {
  width: 100%;
}

.avatar-uploader {
  border-radius: 6px;
  cursor: pointer;
  position: relative;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  border-radius: 3px;
  font-size: 28px;
  color: #8c939d;
  position: absolute;
  top: 0;
  z-index: 999;
  width: 108px;
  height: 108px;
  line-height: 108px !important;
  text-align: center;
}
.avatar {
  z-index: 999;
  border: 1px dashed #d9d9d9;
  position: absolute;
  top: 0;
  width: 108px;
  height: 108px;
  display: block;
}
.el-dialog__header {
    padding: 10px 10px 10px;
    background-color: #0063c7;
}

.el-dialog__title {

    color:#ffffff;
}
</style>
